//
//  OAuthViewController.swift
//  新浪微博
//
//  Created by yzl on 15/7/30.
//  Copyright © 2015年 yjc. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController,UIWebViewDelegate {
// MARK :搭建网页界面
    private lazy var webView = UIWebView()
    // 加载webview个元素，设置代理
    override func loadView() {
        view = webView
        webView.delegate = self
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    //关闭页面
    func close() {
       SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
 // 加载授权页面
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedNetworkTools.oauthUrl()))
    }
// MARK - 实现webview的代理方法
        func webViewDidStartLoad(webView: UIWebView) {
            SVProgressHUD.show()
        }
       
        func webViewDidFinishLoad(webView: UIWebView) {
            SVProgressHUD.dismiss()
        }
    
        func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
            // 获取的是完整的请求字符串
            let urlString = request.URL!.absoluteString
            // 判断是否包含回调地址,如果不包含，你继续加载
            if !urlString.hasPrefix(NetworkTools.sharedNetworkTools.redirectUri) {
           return true
            }
            print("请求参数")
            print("query = \(request.URL?.query)")
            // 如果有？后面的参数query,并且query的前缀包含code，那么就可以进入授权成功
            if let query = request.URL?.query where query.hasPrefix("code=") {
                // 从query中截取授权码
                let code = query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
                print("code = \(code)")
                // 根据获取的状态码，换取token
                loadAccessToken(code)
                close()
                
                //TODO: - 跳转
            }else{// 关闭，返回首页
                close()
            }
            return false
        }
    private func loadAccessToken(code:String) {
        NetworkTools.sharedNetworkTools.loadAccessToken(code) { ( result, error) -> () in
            if error != nil || result == nil {
                
                return
            }
            // 拿到数据
          //  print(result)
/// 字典转模型
            let acc = userAccount(dict: result!)
            
            acc.saveAccount()
            
            
           acc.loadUserInfo({ (error) -> () in
            if error != nil {
                self.netError()
                
//                return
            }
            NSNotificationCenter.defaultCenter().postNotificationName(JCRootViewControllerSwitchNotification, object: false)
            // modal 出来的控制器，最后一定要销毁
            self.close()
    })
           
  }
        
}
    private func netError() {
        SVProgressHUD.showInfoWithStatus("网络不给力")
        // 延时一段时间就关闭
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
        dispatch_after(when, dispatch_get_main_queue(), { () -> Void in
            // 关闭回到首页
            self.close()
        })

    }
    
}
